package com.lill.common.component.xss;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.web.util.HtmlUtils;

import java.io.IOException;

public class XssStringJsonSerializer extends JsonSerializer<String> {
    @Override
    public Class<String> handledType() {
        return String.class;
    }

    @Override
    public void serialize(String value, JsonGenerator jsonGenerator,
                          SerializerProvider serializerProvider) throws IOException {
        if (value != null) {
            if(value.contains("<")||value.contains(">")){
            	String encodedValue = "";
            	if(value.contains("<script>")||value.contains("</script>")){
            		encodedValue = value.replaceAll("<","").replaceAll(">","");
            	}else{
//                spring官方提供特殊字符转义方法
            		encodedValue = HtmlUtils.htmlEscape(value);
            	}
                jsonGenerator.writeString(encodedValue);
            }else{
                jsonGenerator.writeString(value);
            }
        }
    }
}
